<template>
  <div class="model-container">
    <!-- 左侧模型分类 -->
    <div class="sidebar" :class="{ 'collapsed': isCollapsed }">
      <div class="sidebar-header">
        <span class="title">模型分类</span>
        <el-icon class="collapse-icon" @click="toggleCollapse">
          <Fold v-if="!isCollapsed" />
          <Expand v-else />
        </el-icon>
      </div>
      
      <div class="sidebar-content" v-if="!isCollapsed">
        <el-tree
          ref="treeRef"
          :data="categoryTree"
          :props="defaultProps"
          node-key="id"
          :default-expanded-keys="expandedKeys"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              {{ node.label }}
              <div class="node-actions">
                <el-icon @click.stop="addSubCategory(data)"><CirclePlus /></el-icon>
                <el-icon v-if="data.id !== 0" @click.stop="editCategory(data)"><Edit /></el-icon>
                <el-icon v-if="data.id !== 0" @click.stop="deleteCategory(data)"><Delete /></el-icon>
              </div>
            </div>
          </template>
        </el-tree>
        
        <div class="sidebar-footer">
          <el-button type="primary" @click="addRootCategory">添加根分类</el-button>
        </div>
      </div>
    </div>

    <!-- 右侧内容区 -->
    <div class="content">
      <div class="content-header">
        <h2>{{ getCurrentCategoryName() }} 数据模型</h2>
        <el-button type="primary" @click="addModel">
          <el-icon><Plus /></el-icon> 添加模型
        </el-button>
      </div>
      
      <el-table :data="filteredModels" style="width: 100%">
        <el-table-column prop="name" label="模型名称" />
        <el-table-column prop="tableName" label="数据表名" />
        <el-table-column prop="note" label="描述" />
        <el-table-column prop="addDate" label="创建时间" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-icon class="table-icon" @click="editModel(scope.row)"><Edit /></el-icon>
            <el-icon class="table-icon" @click="deleteModel(scope.row)"><Delete /></el-icon>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="isEditingCategory ? '编辑模型分类' : '添加模型分类'" v-model="showCategoryDialog" width="30%">
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称" required>
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input v-model="categoryForm.description" type="textarea" placeholder="请输入分类描述" />
        </el-form-item>
        <el-form-item v-if="categoryForm.parentId !== null" label="父级分类">
          <el-input :value="getParentCategoryName(categoryForm.parentId)" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCategoryDialog = false">取消</el-button>
          <el-button type="primary" @click="saveCategory">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 使用模型表单组件 -->
    <model-form
      v-model:visible="showAddModelDialog"
      :model="currentModel"
      :is-editing="isEditing"
      :category-options="categoryOptions"
      :current-category="currentCategory"
      @saved="loadModels"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Fold, Expand, CirclePlus } from '@element-plus/icons-vue'
import http from '@/utils/request'
import ModelForm from '@/components/model/ModelForm.vue'

// 左侧面板折叠状态
const isCollapsed = ref(false)

// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 获取父分类名称
const getParentCategoryName = (parentId) => {
  let name = ''
  
  const findCategory = (categories, id) => {
    for (const category of categories) {
      if (category.id === id) {
        name = category.name
        return true
      }
      
      if (category.children && category.children.length > 0) {
        if (findCategory(category.children, id)) {
          return true
        }
      }
    }
    
    return false
  }
  
  findCategory(categories.value, parentId)
  return name
}

// 模型分类数据 - 树形结构
const categories = ref([])

// 加载分类数据
const loadCategories = async () => {
  try {
    let param={};
    param.fetch = 1;
    param.depth=1;
    const res = await http.post('/moduleCatalog/list',param)
    if (res.code === 200) {
      categories.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取分类数据失败')
    }
  } catch (error) {
    console.error('获取分类数据出错:', error)
    ElMessage.error('获取分类数据出错，请检查网络连接')
  }
}

// 树形结构配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 构建树形结构的根节点
const categoryTree = computed(() => {
  return [
    {
      id: 0,
      name: '全部分类',
      children: categories.value
    }
  ]
})

// 构建级联选择器的选项
const categoryOptions = computed(() => {
  return JSON.parse(JSON.stringify(categoryTree.value))
})

// 模型数据
const models = ref([])

// 当前选中的分类
const currentCategory = ref(0)

// 当前展开的节点 ID 列表
const expandedKeys = ref([0]) // 默认只展开根节点

// 根据分类ID加载模型数据
const loadModelsByCategory = async (categoryId) => {
  try {
    const params = {
      catalog: categoryId === 0 ? null : categoryId
    }
    
    const res = await http.post('/module/list', params)
    if (res.code === 200) {
      // 处理返回的数据，确保每个模型都有items字段
      models.value = (res.data || []).map(model => {
        // 如果没有items字段，添加一个空数组
        if (!model.items) {
          model.items = []
        }
        return model
      })
    } else {
      ElMessage.error(res.message || '获取模型数据失败')
    }
  } catch (error) {
    console.error('获取模型数据出错:', error)
    ElMessage.error('获取模型数据出错，请检查网络连接')
  }
}

// 加载所有模型数据
const loadModels = async () => {
  await loadModelsByCategory(currentCategory.value)
}

// 处理树节点点击
const handleNodeClick = async (data) => {
  currentCategory.value = data.id
  
  // 加载该分类下的模型数据
  await loadModelsByCategory(data.id)
}

// 根据当前分类过滤模型
const filteredModels = computed(() => {
  // 不再需要在前端过滤，因为后端已经根据分类ID过滤了数据
  return models.value
})

// 获取当前分类名称
const getCurrentCategoryName = () => {
  if (currentCategory.value === 0) {
    return '全部'
  }
  
  let name = ''
  const findName = (cats, id) => {
    for (const cat of cats) {
      if (cat.id === id) {
        name = cat.name
        return true
      }
      
      if (cat.children && cat.children.length > 0) {
        if (findName(cat.children, id)) {
          return true
        }
      }
    }
    
    return false
  }
  
  findName(categories.value, currentCategory.value)
  return name || '未知分类'
}

// 添加/编辑分类相关
const showCategoryDialog = ref(false)
const isEditingCategory = ref(false)
const categoryForm = ref({
  id: null,
  name: '',
  description: '',
  parentId: null
})

// 添加根分类
const addRootCategory = () => {
  isEditingCategory.value = false
  categoryForm.value = {
    id: null,
    name: '',
    description: '',
    parentId: null
  }
  showCategoryDialog.value = true
}

// 添加子分类
const addSubCategory = (parentCategory) => {
  isEditingCategory.value = false
  categoryForm.value = {
    id: null,
    name: '',
    description: '',
    parentId: parentCategory.id
  }
  showCategoryDialog.value = true
}

// 保存分类
const saveCategory = async () => {
  if (!categoryForm.value.name) {
    ElMessage.warning('请输入分类名称')
    return
  }
  
  try {
    let url = '/moduleCatalog/create'
    let method = 'post'
    let data = {
      name: categoryForm.value.name,
      description: categoryForm.value.description,
      parent: categoryForm.value.parentId === null ? null : categoryForm.value.parentId
    }
    
    let res
    if (isEditingCategory.value) {
      data.id = categoryForm.value.id
      res = await http.post('/moduleCatalog/update', data)
    } else {
      res = await http.post('/moduleCatalog/create', data)
    }
    
    if (res.code === 200) {
      ElMessage.success(isEditingCategory.value ? '分类更新成功' : '分类添加成功')
      showCategoryDialog.value = false
      
      // 保存当前展开的节点状态
      if (treeRef.value) {
        const nodes = treeRef.value.store._getAllNodes()
        expandedKeys.value = nodes
          .filter(node => node.expanded)
          .map(node => node.data.id)
      }
      
      // 如果是添加子分类，确保父节点在展开状态
      if (!isEditingCategory.value && categoryForm.value.parentId) {
        if (!expandedKeys.value.includes(categoryForm.value.parentId)) {
          expandedKeys.value.push(categoryForm.value.parentId)
        }
      }
      
      // 重新加载分类数据
      await loadCategories()
      
      // 在下一个渲染周期恢复展开状态
      setTimeout(() => {
        if (treeRef.value) {
          treeRef.value.setExpandedKeys(expandedKeys.value)
        }
      }, 100)
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('保存分类出错:', error)
    ElMessage.error('操作失败，请检查网络连接')
  }
}

// 删除分类
const deleteCategory = async (category) => {
  // 检查是否有子分类
  if (category.children && category.children.length > 0) {
    ElMessage.warning('该分类下有子分类，无法删除')
    return
  }
  
  // 检查是否有关联的模型
  const hasModels = models.value.some(model => model.catalog === category.id)
  if (hasModels) {
    ElMessage.warning('该分类下有关联的模型，无法删除')
    return
  }
  
  try {
    const result = await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？`, 
      '警告', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (result === 'confirm') {
      let param = {}
      param.id = category.id
      const res = await http.post(`/moduleCatalog/delete`, param)
      
      if (res.code === 200) {
        ElMessage.success('分类删除成功')
        
        // 保存当前展开的节点状态
        if (treeRef.value) {
          const nodes = treeRef.value.store._getAllNodes()
          expandedKeys.value = nodes
            .filter(node => node.expanded)
            .map(node => node.data.id)
        }
        
        // 重新加载分类数据
        await loadCategories()
        
        // 在下一个渲染周期恢复展开状态
        setTimeout(() => {
          if (treeRef.value) {
            treeRef.value.setExpandedKeys(expandedKeys.value)
          }
        }, 100)
        
        // 如果当前选中的是被删除的分类，则重置为全部分类
        if (currentCategory.value === category.id) {
          currentCategory.value = 0
          await loadModelsByCategory(0)
        }
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类出错:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 编辑分类
const editCategory = (data) => {
  if (data.id === 0) return // 不能编辑根节点
  
  isEditingCategory.value = true
  categoryForm.value = {
    id: data.id,
    name: data.name,
    description: data.description,
    parentId: data.parentId
  }
  showCategoryDialog.value = true
}

// 模型表单相关
const showAddModelDialog = ref(false)
const isEditing = ref(false)
const currentModel = ref({})

// 添加模型
const addModel = () => {
  isEditing.value = false
  currentModel.value = {}
  showAddModelDialog.value = true
}

// 编辑模型
const editModel = (model) => {
  isEditing.value = true
  currentModel.value = model
  showAddModelDialog.value = true
}

// 删除模型
const deleteModel = async (model) => {
  try {
    const result = await ElMessageBox.confirm(
      `确定要删除模型 "${model.name}" 吗？删除后将无法恢复！`, 
      '警告', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (result === 'confirm') {
      // 使用 POST 请求删除模型，传递 id 参数
      const param = {
        id: model.id
      }
      const res = await http.post('/module/delete', param)
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        // 重新加载模型数据
        loadModels()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模型出错:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 树引用
const treeRef = ref(null)

// 展开全部节点
const expandAll = () => {
  const nodes = treeRef.value.store._getAllNodes()
  nodes.forEach(node => {
    node.expanded = true
  })
}

// 折叠全部节点
const collapseAll = () => {
  const nodes = treeRef.value.store._getAllNodes()
  nodes.forEach(node => {
    if (node.data.id !== 0) { // 保持根节点展开
      node.expanded = false
    }
  })
}

onMounted(() => {
  // 加载分类数据
  loadCategories()
  
  // 加载模型数据
  loadModels()
})
</script>

<style scoped>
.model-container {
  display: flex;
  height: 100%;
  background-color: #f5f7fa;
}

/* 左侧边栏 */
.sidebar {
  width: 260px;
  background: #fff;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  border-radius: 4px 0 0 4px;
}

.sidebar.collapsed {
  width: 64px;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8fafc;
  border-radius: 4px 0 0 0;
}

.sidebar-header .title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.collapse-icon {
  cursor: pointer;
  font-size: 18px;
  color: #606266;
}

.sidebar-content {
  flex: 1;
  overflow: auto;
  padding: 16px 0;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 8px;
}

.node-actions {
  display: none;
}

.tree-node:hover .node-actions {
  display: flex;
  gap: 8px;
}

.node-actions .el-icon {
  font-size: 16px;
  color: #606266;
  cursor: pointer;
}

.node-actions .el-icon:hover {
  color: #409eff;
}

.sidebar-footer {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  text-align: center;
  background-color: #f8fafc;
  border-radius: 0 0 0 4px;
}

/* 右侧内容区 */
.content {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background-color: #fff;
  margin: 0 0 0 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.content-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

/* 表格样式 */
:deep(.el-table) {
  --el-table-header-bg-color: #f8fafc;
  --el-table-border-color: #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 500;
}

/* 表格图标 */
.table-icon {
  font-size: 18px;
  margin: 0 6px;
  cursor: pointer;
  color: #606266;
}

.table-icon:hover {
  color: #409eff;
}

/* 滚动条样式 */
.sidebar-content::-webkit-scrollbar {
  width: 6px;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 3px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: transparent;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: #f8fafc;
  margin: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>

